package initialize

import (
	"context"
	"fmt"
	"os"
	"portal_rpc/global"

	"github.com/elastic/elastic-transport-go/v8/elastictransport"
	"github.com/elastic/go-elasticsearch/v8"
	"go.uber.org/zap"
	"gopkg.in/natefinch/lumberjack.v2"
)

func InitElasticClient(isDebug bool) {

	var err error
	address := fmt.Sprintf("http://%s:%d", global.ServerConfig.Elastic.Host, global.ServerConfig.Elastic.Port)
	config := elasticsearch.Config{
		Addresses: []string{address},
	}
	if isDebug {
		config.Logger = &elastictransport.ColorLogger{
			Output:             os.Stdout,
			EnableRequestBody:  true,
			EnableResponseBody: true,
		}
	} else {
		config.Logger = &elastictransport.JSONLogger{
			Output: &lumberjack.Logger{
				Filename:   "./log/elastic/info.log",
				MaxSize:    500, // megabytes
				MaxBackups: 3,
				MaxAge:     28, // days
			},
			EnableRequestBody:  true,
			EnableResponseBody: true,
		}
	}

	global.ElasticClient, err = elasticsearch.NewTypedClient(config)
	if err != nil {
		zap.L().Panic("initialize elasticsearch failed", zap.Error(err))
		return
	}

	// 创建索引
	exists, err := global.ElasticClient.Indices.Exists("goods").IsSuccess(context.TODO())
	if err != nil {
		zap.L().Panic("get goods index failed", zap.Error(err))
		return
	}

	if !exists {
		// goodsMapping := model.GetMapping()
		// resp, err := global.ElasticClient.Indices.Create("goods").Request(&create.Request{
		// 	Mappings: goodsMapping,
		// }).Do(context.TODO())
		// if err != nil {
		// 	if esErr, ok := err.(*types.ElasticsearchError); ok {
		// 		zap.L().Error("create index goods failed", zap.String("error", *esErr.ErrorCause.Reason))
		// 	} else {
		// 		zap.L().Panic("create index goods failed", zap.Error(err))
		// 		return
		// 	}
		// } else {
		// 	if resp.Acknowledged {
		// 		zap.L().Info("create index goods success")
		// 	} else {
		// 		zap.L().Error("create index goods failed")
		// 	}
		// }
	}
}
